<script setup lang="ts">
import type { FormInstance, FormItemRule, FormRules } from 'element-plus'
import MfaLogin from './components/MfaLogin.vue'

import { HOME_URL } from '@/constants'

import { encrypt, setCookie, setCookies } from '@/utils'

const router = useRouter()

const loginMode = ref('account')
const accountLoginWay = ref('accountName')
const userLoginWay = ref('userName')
const loginLoading = ref(false)
const loginFormRef = ref<FormInstance>(null)
const imageCodeRef = ref(null)

const isAccountMode = computed(() => loginMode.value === 'account')

const mfaVisible = ref(false)
const mfaProp = reactive({
  accountUuid: '',
  userUuid: '',
})
const accountWayOptions = {
  accountName: '账户名',
  phone: '手机号',
  email: '邮箱',
}
const userWayOptions = {
  userName: '用户名',
  userPhone: '手机号',
  userEmail: '邮箱',
}

const emailRule: FormItemRule[] = [
  {
    required: true,
    type: 'email',
    message: '请输入邮箱地址',
    trigger: 'blur',
  },
  {
    pattern: /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/,
    message: '请输入正确的邮箱地址',
    trigger: 'blur',
  },
]
const phoneRule: FormItemRule[] = [
  { required: true, message: '请输入手机号', trigger: 'blur' },
  {
    pattern: /^((0\d{2,3}-\d{7,8})|(1[3456789]\d{9}))$/,
    message: '请输入正确的手机号',
    trigger: 'blur',
  },
]
const form = reactive({
  accountName: '',
  userName: '',
  password: '',
  imageCode: '',
  imageUuid: '',
  mfaType: '',
  mfaCode: '',
})
const name = computed(() => isAccountMode.value ? form.accountName : form.userName)

const formRules = reactive<FormRules>({
  accountName: [
    { required: true, message: '请输入账户名', trigger: 'blur' },
  ],
  userName: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
  ],
  phone: phoneRule,
  email: emailRule,
  userEmail: emailRule,
  userPhone: phoneRule,
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  imageCode: [{ required: true, message: '请输入验证码', trigger: 'blur' }],
})

watch(loginMode, (val, oldVal) => {
  if (oldVal === 'user')
    form.userName = ''
  else
    form.accountName = ''
})
watch(accountLoginWay, (val, oldVal) => form[oldVal] = '')
watch(userLoginWay, (val, oldVal) => form[oldVal] = '')
function setCookiesDone(inventory) {
  const { uuid: sessionid, accountUuid, type: accountType } = inventory
  setCookie('isAccount', `${isAccountMode.value}`)
  setCookies({
    sessionid,
    accountUuid,
    accountType,
    accountName: name.value,
    isAccount: isAccountMode.value,
  })
}
async function mfaDone(data) {
  const newForm = Object.assign({}, form, data, { password: encrypt(form.password) })
  loginLoading.value = true
  const apikey = isAccountMode.value ? 'LogInByAccount' : 'LogInByUser'
  const { success, inventory, error, needChangePwd } = await useRequest(apikey, newForm) as any
  loginLoading.value = false
  if (success) {
    needChangePwd && notifyChangePwd()
    setCookiesDone(inventory)
    mfaVisible.value = false
    router.replace(HOME_URL)
  }
  else {
    ElNotification({
      type: 'error',
      message: error.details,
    })
  }
}
function toRegister() {
  router.push('/register')
}
function notifyChangePwd() {
  ElNotification({
    type: 'info',
    message: '系统检测账号长期未修改密码，为提高安全性，建议立即修改密码！',
  })
}
function toDownload() {
  router.push('/download')
}
function confirm() {
  router.replace(HOME_URL)
/*   loginFormRef.value?.validate(async (valid) => {
    if (valid) {
      loginLoading.value = true
      const newForm = Object.assign({}, form, { password: encrypt(form.password) })
      const apikey = isAccountMode.value ? 'LogInByAccount' : 'LogInByUser'
      const { success, needChangePwd, inventory = {}, error, accountUuid = '', userUuid = '' } = await useRequest(apikey, newForm) as any
      loginLoading.value = false
      if (success) {
        if (inventory.type === 'SystemAdmin')
          return
        needChangePwd && notifyChangePwd()

        // 2.添加动态路由
        // await initDynamicRouter()
        setCookiesDone(inventory)
        router.replace(HOME_URL)
      }
      else {
        if (error.code === 'ID.2000') {
          mfaProp.accountUuid = accountUuid
          mfaProp.userUuid = userUuid
          mfaVisible.value = true
        }
        else {
          imageCodeRef.value.getCode()
        }
      }
    }
  }) */
}

const debounceLogin = useDebounceFn(() => {
  confirm()
}, 300)
const appTitle = inject('appTitle')
</script>

<template>
  <div class="bg-wrap wh-screen flex-center p-5 2xl:pr-50 md:pr-30 xl:pr-60">
    <el-form
      ref="loginFormRef"
      class="login-form w-full md:(ml-auto w-103)"
      :model="form"
      :rules="formRules"
      size="large"
    >
      <h1 class="flex-center gap-2">
        <img src="/logo.svg" style="vertical-align: middle;" width="50" height="50" alt="process">
        <span text-3xl>
          {{ appTitle }}
        </span>
      </h1>
      <el-form-item>
        <el-radio-group v-model="loginMode" class="mx-auto">
          <el-radio-button value="account">
            账户登录
          </el-radio-button>
          <el-radio-button value="user">
            子用户登录
          </el-radio-button>
        </el-radio-group>
      </el-form-item>
      <!-- 账户 -->
      <el-form-item
        :prop="accountLoginWay"
        :rules="formRules[accountLoginWay]"
      >
        <el-input
          v-model="form[accountLoginWay]"
          class="login-input"
          :placeholder="`请输入${accountWayOptions[accountLoginWay]}`"
        >
          <template #prepend>
            <select v-model="accountLoginWay" class="login-way-select" placeholder="请选择">
              <option label="账户名" value="accountName" />
              <option label="手机号" value="phone" />
              <option label="邮箱" value="email" />
            </select>
          </template>
        </el-input>
      </el-form-item>

      <!-- 用户名 -->
      <el-form-item
        v-if="loginMode === 'user'"
        key="user"
        :prop="userLoginWay"
        :rules="formRules[userLoginWay]"
      >
        <el-input
          v-model="form[userLoginWay]"
          class="login-input"
          :placeholder="`请输入${userWayOptions[userLoginWay]}`"
        >
          <template #prepend>
            <select v-model="userLoginWay" class="login-way-select" placeholder="请选择">
              <option label="用户名" value="userName" />
              <option label="手机号" value="userPhone" />
              <option label="邮箱" value="userEmail" />
            </select>
          </template>
        </el-input>
      </el-form-item>

      <el-form-item prop="password">
        <el-input
          v-model="form.password"
          class="login-input"
          type="password"
          placeholder="请输入密码"
          show-password
        />
      </el-form-item>
      <el-form-item prop="imageCode" class="flex-center">
        <el-input
          v-model.trim="form.imageCode"
          class="flex-1"
          placeholder="请输入验证码"
          @keyup.enter="debounceLogin"
        />
        <ImageCode ref="imageCodeRef" v-model="form.imageUuid" />
      </el-form-item>
      <el-form-item>
        <el-button
          class="w-full"
          type="primary"
          round
          :loading="loginLoading"
          @click="debounceLogin"
        >
          登录
        </el-button>
      </el-form-item>
    </el-form>
    <MfaLogin v-model="mfaVisible" :account-uuid="mfaProp.accountUuid" :user-uuid="mfaProp.userUuid" @done="mfaDone" />
  </div>
</template>

<style lang="scss" scoped>
.bg-wrap {
  background-image: url(/login-bg.png);
  background-size: auto 550px;
  background-repeat: no-repeat;
}

@media (max-width: 1024px) {
  .bg-wrap {
    background-position: center center;
  }
}
@media (min-width: 1024px) {
  .bg-wrap {
    background-position: 100px center;
  }
}
@media (min-width: 1280px) {
  .bg-wrap {
    background-position: 200px center;
  }
}
.login-form {
  padding: 15px 30px;
  border-radius: 8px;
  background-color: #fff;
  box-shadow: 0 0 8px #ddd;
  transition: height 0.3s ease-in-out;
  h1 {
    font-weight: 600;
    padding-top: 45px;
    padding-bottom: 24px;
    text-align: center;
  }
}
.error-info {
  color: #f56c6c;
  font-size: 12px;
  line-height: 1;
  padding-top: 4px;
}

.login-way-select {
  width: 70px;
  border: none;
  outline: none;
  font-size: 14px;
  background: transparent;
}
:deep(.el-input-group__prepend) {
  padding: 0 10px !important;
}
</style>
